package com.coscon.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    public CustomFormAuthenticationFilter(){
        this.setRememberMeParam("rememberMe");
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                // 放行 allow them to see the login page ;)
                return true;
            }
        } else {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            if (isAjax(httpRequest)) {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);  
                httpServletResponse.sendError(401);//返回401状态码，前台获取这个则为需要登录
                return false;
            } else {  
                saveRequestAndRedirectToLogin(request, response); 
            }  
            return false;
        }
    }
    /**
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
    	   boolean ajax = "XMLHttpRequest".equals( request.getHeader("X-Requested-With") );
           String ajaxFlag = null == request.getParameter("ajax") ?  "false": request.getParameter("ajax") ;
           boolean isAjax = ajax || "true".equalsIgnoreCase(ajaxFlag);
        return  isAjax ;
    }
    
}